﻿<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-left">
        <img alt="Login Illustration" class="illustration" src="@/assets/images/illustrations/hero.png" />
      </div>
      <div class="login-right">
        <div class="login-box">
          <div class="login-header">
            <h2>{{ isLogin ? "欢迎回来" : "用户注册" }}</h2>
            <p>{{ isLogin ? "请输入您的凭据以继续" : "创建您的账号" }}</p>
          </div>

          <!-- 登录表单 -->
          <el-form v-if="isLogin" :model="loginForm" :rules="loginRules" ref="loginFormRef" @submit.native.prevent="handleLogin">
            <el-form-item prop="username">
              <el-input v-model.trim="loginForm.username" placeholder="用户名" :prefix-icon="User" size="large" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model.trim="loginForm.password" type="password" placeholder="密码" :prefix-icon="Lock" show-password size="large" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading" native-type="submit">登 录</el-button>
            </el-form-item>

            <div class="form-footer">
              <span>还没有账号？</span>
              <a @click="toggleForm">立即注册</a>
            </div>
          </el-form>

          <!-- 注册表单 -->
          <el-form v-else :model="registerForm" :rules="registerRules" ref="registerFormRef" @submit.native.prevent="handleRegister">
            <el-form-item prop="username">
              <el-input v-model.trim="registerForm.username" placeholder="用户名" :prefix-icon="User" size="large" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model.trim="registerForm.password" type="password" placeholder="密码" :prefix-icon="Lock" show-password size="large" />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input v-model.trim="registerForm.confirmPassword" type="password" placeholder="确认密码" :prefix-icon="Lock" show-password size="large" />
            </el-form-item>

            <el-form-item prop="email">
              <el-input v-model.trim="registerForm.email" placeholder="邮箱地址" :prefix-icon="Message" size="large" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="login-button" @click="handleRegister" :loading="loading" native-type="submit">注 册</el-button>
            </el-form-item>

            <div class="form-footer">
              <span>已有账号？</span>
              <a @click="toggleForm">立即登录</a>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref } from "vue"
import { Lock, Message, User } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import { useUsersStore } from "@/stores/modules/user"
import { register } from "@/api/modules/user"
import { handleError, handleSuccess } from "@/utils/core/error-handler"
import { commonRules } from "@/utils/validate/rules"
import { confirmPasswordValidator } from "@/utils/validate/validators"

const usersStore = useUsersStore()
const router = useRouter()

const loginFormRef = ref(null)
const registerFormRef = ref(null)
const loading = ref(false)
const isLogin = ref(true) // 切换登录注册表单

// 登录表单
const loginForm = reactive({
  username: "",
  password: ""
})

// 注册表单
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  email: ""
})

// 登录表单验证规则
const loginRules = {
  username: commonRules.username,
  password: commonRules.password
}

// 注册表单验证规则
const registerRules = {
  username: commonRules.username,
  password: commonRules.password,
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: confirmPasswordValidator(computed(() => registerForm.password)), trigger: "blur" }
  ],
  email: commonRules.email
}

// 切换登录注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        const loginSuccess = await usersStore.login({
          username: loginForm.username,
          password: loginForm.password
        })

        if (loginSuccess) {
          // 跳转到首页
          router.push("/dashboard")
        }
      } catch (error) {
        handleError(error, {
          message: "登录失败，请重试",
          context: "Login"
        })
      } finally {
        loading.value = false
      }
    }
  })
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true

    const response = await register({
      username: registerForm.username,
      password: registerForm.password,
      email: registerForm.email
    })

    if (response.code === 200) {
      handleSuccess("注册成功，请登录")

      registerForm.username = ""
      registerForm.password = ""
      registerForm.confirmPassword = ""
      registerForm.email = ""
      isLogin.value = true
    } else {
      handleError(new Error(response.message || "注册失败"), {
        message: "注册失败",
        context: "Register"
      })
    }
  } catch (error) {
    handleError(error, {
      message: "注册失败，请重试",
      context: "Register"
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;

.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, $color-primary-light-9 0%, $bg-color-layout 100%);
}

.login-card {
  width: 90%;
  max-width: 1000px;
  min-height: 600px;
  background: $bg-color-white;
  border-radius: $border-radius-xl;
  display: flex;
  overflow: hidden;
  box-shadow: $box-shadow-lg;
  animation: fadeIn 0.8s ease-out;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, $color-primary, $color-primary-dark-2);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: $spacing-xl;
  position: relative;
  overflow: hidden;

  .illustration {
    width: 100%;
    max-width: 450px;
    height: auto;
    object-fit: contain;
    opacity: 0.95;
    filter: drop-shadow(0 10px 30px rgba(0, 0, 0, 0.2));
  }
}

.login-right {
  flex: 1;
  padding: $spacing-3xl;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 100%;
  max-width: 380px;

  .login-header {
    text-align: center;
    margin-bottom: $spacing-2xl;

    h2 {
      font-size: $font-size-2xl;
      font-weight: $font-weight-bold;
      color: $color-text-primary;
      margin-bottom: $spacing-sm;
    }

    p {
      font-size: $font-size-base;
      color: $color-text-secondary;
    }
  }

  .login-button {
    width: 100%;
    height: 44px;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    margin-top: $spacing-lg;
  }

  .form-footer {
    margin-top: $spacing-lg;
    text-align: center;
    font-size: $font-size-sm;
    color: $color-text-secondary;

    a {
      color: $color-primary;
      cursor: pointer;
      margin-left: $spacing-xs;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

@media (max-width: 768px) {
  .login-card {
    flex-direction: column;
    min-height: auto;
    max-width: 95%;
  }

  .login-left {
    display: none;
  }

  .login-right {
    padding: $spacing-xl;
  }

  .login-box {
    max-width: 100%;
  }
}

/* 使用全局动画定义 */
</style>
